﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace NotifyForCreateProject
{
    public class HandleAtProjCreatedMgr
    {
        /// <summary>
        /// 服务实例缓存
        /// </summary>
        private static ConcurrentDictionary<string, IHandleAtProjCreated> Services = new ConcurrentDictionary<string, IHandleAtProjCreated>();
        
        /// <summary>
        /// 获取服务实例（如果没有则添加）
        /// </summary>
        /// <param name="classFullName"></param>
        /// <returns></returns>
        private static IHandleAtProjCreated GetOrAdd(string classFullName)
        {
            var type = Type.GetType(classFullName);
            if(!typeof(IHandleAtProjCreated).IsAssignableFrom(type) || !type.IsClass || type.IsAbstract )
            {
                // 处理（包括但不限于抛出异常）
                return null;
            }

            return Services.GetOrAdd($"{type.FullName},{type.Assembly.FullName}", (IHandleAtProjCreated)Activator.CreateInstance(type));
        }

        /// <summary>
        /// 模拟配置获取
        /// </summary>
        private static string[] GetConfigs()
        {
            return new string[] { typeof(HandleAtProjCreated_01).FullName, typeof(HandleAtProjCreated_03).FullName };
        }

        /// <summary>
        /// 根据所获取配置 获取当前启用服务实例
        /// </summary>
        /// <returns></returns>
        private static List<IHandleAtProjCreated> GetServices()
        {
            var configs = GetConfigs();

            if(configs == null || configs.Length == 0)
            {
                return null;
            }

            return configs.ToList().Select(config => GetOrAdd(config)).ToList();
        }

        /// <summary>
        /// 项目创建后的处理
        /// </summary>
        /// <param name="projects">项目列表</param>
        public static void Handle(IEnumerable<ProjectModel> projects)
        {
            if(projects == null || !projects.Any())
            {
                return;
            }

            var services = GetServices();
            if (services == null || services.Count == 0)
            {
                return;
            }

            foreach( var service in services)
            {
                service.Handle(projects);
            }
        }
    }
}
